from django.shortcuts import render, redirect
from webapp.models import Admin
from webapp.modelforms.mymodelform import AdminModelForm


def admin_list(request):
    # 获取所有数据，返回给前端页面
    data = Admin.objects.all()
    form = AdminModelForm()
    return render(request, "admin_list.html", {"data": data, "form": form})


def admin_add(request):
    html_title = "新建管理员"
    if request.method == 'POST':
        form = AdminModelForm(data=request.POST)
        if form.is_valid():
            form.save()
            return redirect('/admin/list')
        else:
            return render(request, "change.html", {"html_title": html_title, "form": form})
    form = AdminModelForm()
    return render(request, "change.html", {'html_title': html_title, "form": form})


def admin_delete(request, nid):
    Admin.objects.filter(id=nid).delete()
    return redirect('/admin/list')


def admin_edit(request, nid):
    html_title = "编辑管理员"
    admin = Admin.objects.filter(id=nid).first()
    if not admin:
        return render(request, 'error.html', {'msg': '数据不存在'})
    if request.method == 'POST':
        form = AdminModelForm(data=request.POST, instance=admin)
        if form.is_valid():
            form.save()
            return redirect('/admin/list')
        else:
            return render(request, "change.html", {'html_title': html_title, "form": form})
    form = AdminModelForm(instance=admin)
    return render(request, "change.html", {'html_title': html_title, "form": form})
